package project1.service;

import project1.dao.GoodsDao;
import project1.dao.GoodsDaoImpl;
import project1.model.Goods;
import project1.model.Spec;
import project1.model.Type;
import project1.model.bo.GoodsBO;
import project1.model.bo.SpecBO;
import project1.model.bo.TypeBO;
import project1.view.TypeGoodsVO;

import java.util.ArrayList;
import java.util.List;

public class GoodesServiceImpl implements GoodsService {
    private GoodsDao goodsDao = new GoodsDaoImpl();
    @Override
    public List<Type> getType() {
        return goodsDao.getType();
    }

    @Override
    public List<TypeGoodsVO> getGoodsByType(String typeId) {

        return goodsDao.getGoodsType(typeId);
    }

    /**
     * 新增商品表price、stockNum需要通过specList运算得到
     * 1.保存数据到商品表
     * 2.拿到商品表刚刚插入的商品id
     * 3.将该id以及spec数据保存到spec规格表
     * @param goodsBO
     */
    @Override
    public void addGoods(GoodsBO goodsBO) {
        List<SpecBO> specList = goodsBO.getSpecList();
        double price = specList.get(0).getUnitPrice();
        int stockNum = specList.get(0).getStockNum();
        for (int i = 1 ; i < specList.size() ; i++){
            if (price > specList.get(i).getUnitPrice()){
                price = specList.get(i).getUnitPrice();
            }
            if (stockNum < specList.get(i).getStockNum()){
                stockNum = specList.get(i).getStockNum();
            }
        }
        Goods goods = new Goods(null,goodsBO.getImg(),goodsBO.getName(),price,goodsBO.getTypeId(),stockNum,goodsBO.getDesc());
        goodsDao.addGoods(goods);
        //该id值就是goods表新增的商品的id
        int id = goodsDao.lastInsertId();
        List<Spec> specs = new ArrayList<Spec>();
        for (SpecBO specBO : specList) {
           Spec spec = new Spec(null,specBO.getSpecName(),specBO.getStockNum(),specBO.getUnitPrice(),id);
           specs.add(spec);
        }
        goodsDao.addSpecs(specs);

    }

    @Override
    public void addType(TypeBO typeBO) {
        goodsDao.addType(typeBO);
    }

    @Override
    public void deleteType(String typeId) {
        goodsDao.deleteType(typeId);
    }
}
